package cn.iocoder.yudao.module.wrzj.controller.app.wrzjuser;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.wrzj.controller.app.BaseWrzjController;
import cn.iocoder.yudao.module.wrzj.controller.app.wrzjuser.vo.AppWrzjUserRespVO;
import cn.iocoder.yudao.module.wrzj.dal.dataobject.wrzjuser.WrzjUserDO;
import cn.iocoder.yudao.module.wrzj.service.wrzjuser.WrzjUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wrzj/user/wx")
public class WxMaUserController extends BaseWrzjController {

    private final WxMaService wxMaService;

    @Resource
    private WrzjUserService userService;

    /**
     * 默认账号登录
     * @return
     */
    @GetMapping("/defaultLogin")
    public CommonResult<AppWrzjUserRespVO> login() {
        long defaultUid = 5;
        WrzjUserDO wrzjUserDO = userService.getUser(defaultUid);
        AppWrzjUserRespVO appWrzjUserRespVO = BeanUtils.toBean(wrzjUserDO, AppWrzjUserRespVO.class);
        appWrzjUserRespVO.setToken(generateUserToken(String.valueOf(wrzjUserDO.getId())));
        userService.initGreatmanScore(defaultUid);
        return success(appWrzjUserRespVO);
    }

    /**
     * 登录接口
     */
    @GetMapping("/login")
    public CommonResult<AppWrzjUserRespVO> login(String code) {
        if (StringUtils.isBlank(code)) {
            throw new RuntimeException("code can not be null!");
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            log.info(session.getSessionKey());
            log.info(session.getOpenid());
            WrzjUserDO wrzjUserDO = userService.wxLogin(session.getOpenid());

            AppWrzjUserRespVO appWrzjUserRespVO = BeanUtils.toBean(wrzjUserDO, AppWrzjUserRespVO.class);
            appWrzjUserRespVO.setToken(generateUserToken(String.valueOf(wrzjUserDO.getId())));
            return success(appWrzjUserRespVO);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    public String info(@PathVariable String appid, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return JsonUtils.toJsonString(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        // 用户信息校验
        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            WxMaConfigHolder.remove();//清理ThreadLocal
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        WxMaConfigHolder.remove();//清理ThreadLocal
        return JsonUtils.toJsonString(phoneNoInfo);
    }

}
